package hwr.iamdr.Service;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.*;
import javax.servlet.ServletException;

import com.google.appengine.api.datastore.*;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.gson.stream.JsonWriter;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet
{
	static final DatastoreService dataStore = DatastoreServiceFactory.getDatastoreService();
	static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

	Entity FromEmailPassword(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
	{
		String email = req.getParameter("email");
		if(email == null)
			return null;

		String password = req.getParameter("password");
		if(password != null && password.length() >= 6)
		{
			try
			{
				@SuppressWarnings("unused")
				InternetAddress emailAddr = new InternetAddress(email);
			}
			catch(AddressException e)
			{
				logger.log(Level.WARNING,"Invalid EMail : " + email);
				resp.getWriter().write("Invalid EMail : " + email);
				resp.setStatus(1);
				return null;
			}

			Query query = new Query("Member");
			query.addFilter("email",FilterOperator.EQUAL,email);
			Entity entity = dataStore.prepare(query).asSingleEntity();
			if(entity == null)
			{
				logger.log(Level.WARNING,"EMail " + email + " was Not registered yet");
				resp.getWriter().write("You was Not registered yet");
				resp.setStatus(2);
				return null;
			}

			if(password.equals(entity.getProperty("password")))
				return entity;
		}

		logger.log(Level.WARNING,"EMail : " + email + " : Try to login with " + password + " Password");
		resp.getWriter().write("EMail " + email + " was login with wrong password");
		resp.setStatus(3);
		return null;
	}

	void ToMainPage(HttpServletRequest req,HttpServletResponse resp,Entity entity) throws IOException
	{
		logger.log(Level.INFO,"User " + entity.getKey().getId() + " logged in");
		req.getSession().setAttribute("UserLogin",KeyFactory.keyToString(entity.getKey()));

		JsonWriter writer	= new JsonWriter(resp.getWriter());
		writer.beginObject();
		writer.name("code");
		writer.value(1);
		writer.endObject();
		writer.close();
	}

	@Override
	protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
	{
		Entity entity = MainServlet.UserSession(req);
		if(entity == null)
			return;

		String PID = req.getParameter("PID");
		String Name = req.getParameter("Name");
		if(Name == null || Name.length() < 2)
		{
			resp.getWriter().write("Invalid Name");
			resp.setStatus(0);
			return;
		}

		if(!(Boolean)entity.getProperty("activated"))
		{
			logger.log(Level.WARNING,"EMail " + entity.getProperty("email") + " was Not registered yet");
			resp.getWriter().write("You are not registered yet");
			resp.setStatus(3);
		}
		else
		{
			entity.setProperty("Name",Name);
			entity.setProperty("PID",PID);

			String DID = req.getParameter("DID");
			if(DID != null)
				entity.setProperty("DID",Name);
			String UID = req.getParameter("UID");
			if(UID != null)
				entity.setProperty("UID",UID);

			dataStore.put(entity);

			ToMainPage(req,resp,entity);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
	{
		Entity entity = FromEmailPassword(req,resp);
		if(entity == null)
		{
			entity = MainServlet.UserSession(req);
			if(entity == null)
				return;
		}

		String isCookie = req.getParameter("cookie");
		if(isCookie != null && isCookie.equals("true"))
		{
			for(Cookie cookie : req.getCookies())
			{
				cookie.setMaxAge(60 * 60 * 24 * 7);
				resp.addCookie(cookie);
			}
		}

		if(!(Boolean)entity.getProperty("activated"))
		{
			logger.log(Level.INFO,"User " + entity.getKey() + " request activation");

			JsonWriter writer	= new JsonWriter(resp.getWriter());
			writer.beginObject();
			writer.name("code");
			writer.value(3);
			writer.endObject();
			writer.close();
		}
		else if(entity.getProperty("Name") == null)
		{
			logger.log(Level.INFO,"User " + entity.getKey() + " need init data");

			JsonWriter writer	= new JsonWriter(resp.getWriter());
			writer.beginObject();
			writer.name("code");
			writer.value(2);
			writer.name("key");
			writer.value(String.format("%08X",entity.getKey().getId()));
			writer.endObject();
			writer.close();
		}
		else ToMainPage(req,resp,entity);
	}
}
